package com.gok.core.shiro.realm;

import com.gok.core.shiro.cache.MyByteSource;
import com.gok.server.pojo.User;
import com.gok.util.MapAndObjectUtil;
import com.gok.util.RedisUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author: Administrator
 * @create time: 2020/12/21 19:31
 * @description:  自定义的realm
 */
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MapAndObjectUtil mapAndObjectUtil;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //获取传过来的用户名
        String username=token.getUsername();
        //通过用户名获取缓存中的map
        Map map = redisUtil.hmget(username);

        User fictitious=null;
        try{
           fictitious= (User) mapAndObjectUtil.toObject(map,User.class);
            //如果用户不存在，那么抛出用户不存在异常
            if(fictitious==null){
                throw new UnknownAccountException("用户不存在");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        SimpleAuthenticationInfo simple=new SimpleAuthenticationInfo(username,fictitious.getPassword(),new MyByteSource(fictitious.getSalt()),this.getName());
        return simple;
    }
}
